<template>
  <div class="ditchBox">
      <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">
        <FormItem label="规则类型" prop="ruleType">
          <RadioGroup v-model="dataModule.ruleType" @on-change="handleTypeGadio">
            <Radio v-for="item in typeRadioData" :key="item.value" :label="item.value">{{item.label}}</Radio>
          </RadioGroup>
        </FormItem>

        <FormItem label="所属商户" prop="merchantSelect">
          <Select v-model="dataModule.merchantSelect" :label-in-value="true" placeholder="请选择" v-if="isView" @on-change="bindleMCode">
            <Option v-for="(item, index) in merchantNameSelect" :key="item + index" :value="item.value">{{ item.label }}</Option>
          </Select>
          <span v-else>{{dataModule.merchantName}}</span>
        </FormItem>

        <FormItem label="所属产品" prop="productSelect">
          <Select v-model="dataModule.productSelect" :label-in-value="true" placeholder="请选择" v-if="isView" @on-change="bindleProductCode">
            <Option v-for="(item, index) in productNameSelect" :key="index" :value="item.value">{{ item.label }}</Option>
          </Select>
          <span v-else>{{dataModule.productName}}</span>
        </FormItem>
        <FormItem label="产品编码" >
          <Input type="text" v-model="dataModule.productCode" v-if="isView" />
          <span v-else>北京市</span>
        </FormItem>
        <FormItem prop="ruleName" label="规则名称">
          <Input type="text" v-model="dataModule.ruleName" />
        </FormItem>
        <FormItem label="结算类型" prop="settlementType">
          <Select v-model="dataModule.settlementType" placeholder="请选择" @on-change="handleCloseType">
            <Option v-for="(item, index) in closeTypeData" :key="item + index" :value="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="productPrice" label="产品单价">
          <Input type="text" v-model="dataModule.productPrice" />
        </FormItem>

        <Row>
          <Col span="11">
            <FormItem label="清分周期类型" prop="clearingCycleMode">
              <Radio-group v-model="dataModule.clearingCycleMode">
                  <Radio label="male">天</Radio>
                  <Radio label="female">月</Radio>
              </Radio-group>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem prop="clearingCycleValue" label="清分周期值">
              <Input type="text" v-model="dataModule.clearingCycleValue" />
            </FormItem>
          </Col>
        </Row>

        <FormItem prop="clearingCycleValueExt" label="清分周期拓展值">
          <Input type="text" v-model="dataModule.clearingCycleValueExt" />
        </FormItem>
        <div class="introduce">
          <span class="introduceOne">按天： 无需填写</span>
          <span>按月： 填写整数，表示几号</span>
        </div>
        <FormItem label="清分规则" :prop="closeTypeDataType ? 'clearingRule' : ''">
          <div v-if="!closeTypeDataType">百分比</div>
          <Radio-group v-model="dataModule.clearingRule" v-else>
            <Radio label="0">百分比</Radio>
            <Radio label="1">固定金额</Radio>
          </Radio-group>
        </FormItem>
        <!-- <FormItem label="清分规则" prop="clearRule" v-else>
          <div>百分比</div>
        </FormItem> -->
        <Row>
          <Col span="12">
            <FormItem label="平台应收" :prop="closeTypeDataType ? 'platformReceivable' : ''">
              <Input type="text" v-model="dataModule.platformReceivable" v-if="closeTypeDataType"/>
              <div v-else>100%</div>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="商户应收" :prop="closeTypeDataType ? 'merchantReceivable' : ''">
              <Input type="text" v-model="dataModule.merchantReceivable"  v-if="closeTypeDataType"/>
              <div v-else>0%</div>
            </FormItem>
          </Col>
        </Row>

        <FormItem label="有效时间" prop="validTime">
          <DatePicker :value='[dataModule.effectiveDate, dataModule.expireDate]' format="yyyy-MM-dd" type="daterange" split-panels placeholder="请选择" @on-change="setDateRange" clearable></DatePicker>
        </FormItem>
        <FormItem label="优先级" prop="priorityLevel">
          <Input type="text" v-model="dataModule.priorityLevel" />
        </FormItem>

        <div style="text-align: center; margin-top: 20px">
          <Button style="margin-right: 10px" @click="handleSubmitCancel('dataModule')">取消</Button>
          <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
        </div>
      </Form>
  </div>
</template>
<script>
import config from "@/utils/config";
import { namespace } from "../module/commercial.js";
import {
  Button,
  Input,
  Modal,
  Message,
  Col,
  Row,
  Form,
  FormItem,
  DatePicker,
  Select,
  Option,
  Card,
  Radio,
  RadioGroup
} from "view-design";
import Loading from "@/components/Loading";
import RemoteSelect from "@/components/RemoteSelect";
import RemoteTableSelect from "@/components/RemoteTableSelect";
import SearchBar from "@/components/SearchBar";
import Uuid from "uuid";
import Authc from "@/components/Authc";
import appService from "@/utils/appService";
export default {
  components: {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Radio,
    RadioGroup
  },
  props: ["id"],
  beforeMount: async function() {
    let id = this.$route.query.id;
    let response = await this.$store.dispatch(`${namespace}/getDetail`, id);
    if (response.errorCode === 0) {
      this.dataModule = response.data
      let time = ["2024-04-06", "2024-04-08"]
      this.dataModule.beginTime = time
      console.log( this.dataModule)

      this.dataModule.channelListType = []
      for (let i = 0; i < response.data.channelList.length; i++) {
        this.dataModule.channelListType.push(response.data.channelList[i].paymentChannelCode)
        for (let j = 0; j < this.selectData.length - 1; j++) {
          if (response.data.channelList[i].paymentChannelCode == this.selectData[j].value) {
            this.dataModule.channelList[i].paymentChannelName = this.selectData[j].label
          }
        }
      }
      this.channelListData = this.dataModule.channelList
    }
  },
  data: function() {
    let vm = this;
    return {
      taxpayerId: this.$route.params.id,
      formRef: Uuid.v1(),
      isView: true,
      dataModule: {},
      columns: [],
      channelListData: [],  // 渠道List
      typeRadioData: [
        {
          label: "产品规则",
          value: 1
        },
        {
          label: "通用规则",
          value: 2
        }
      ],
      closeTypeDataType: true,
      merchantNameSelect: [
        {
          label: "商户名称1",
          value: 1
        },
        {
          label: "商户名称2",
          value: 2
        },
        {
          label: "商户名称3",
          value: 3
        }
      ],
       // 所属产品
      productNameSelect: [
        {
          label: "产品111",
          value: "1"
        },
        {
          label: "产品222",
          value: "2"
        }
      ],
      // 结算类型
      closeTypeData: [
        {
          label: "清分",
          value: "0"
        },
        {
          label: "结算",
          value: "1"
        }
      ],
      // 渠道选择
      selectData: [
        {
          value: '1',
          label: '招总行渠道'
        },
        {
          value: '2',
          label: '招渠道'
        },
        {
          value: '3',
          label: '招111渠道'
        },
        {
          value: '4',
          label: '招2222渠道'
        }
      ],
      // 机构名称
      oNameSelect: [],
      // 结算账户类型
      aNameSelect: [
        {
          value: '0',
          label: '招行'
        },
        {
          value: '1',
          label: '微信'
        },
        {
          value: '2',
          label: '支付宝'
        },
        {
          value: '3',
          label: '线下'
        }
      ],
     ruleValidate: {
        ruleType: [
          {
            required: true,
            type: "number",
            message: "请选择",
            trigger: "change"
          }
        ],
        merchantSelect: [
          {
            required: true,
            type: "number",
            message: "请选择",
            trigger: "change"
          }
        ],
        productSelect: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        ruleName: [{ required: true, message: "请填写", trigger: "blur" }],
        settlementType: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        productPrice: [{ required: true, message: "请填写", trigger: "blur" }],
        clearingCycleMode: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        clearingCycleValue: [
          { required: true, message: "请填写", trigger: "blur" }
        ],
        clearingCycleValueExt: [
          { required: true, message: "请填写", trigger: "blur" }
        ],
        clearingRule: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        platformReceivable: [
          { required: true, message: "请填写", trigger: "blur" }
        ],
        merchantReceivable: [
          { required: true, message: "请填写", trigger: "blur" }
        ],
        validTime: [
          {
            type: "array",
            required: true,
            message: "有效期不能为空",
            fields: {
              0: {
                required: true,
                message: "有效期不能为空",
                trigger: "change"
              },
              1: {
                required: true,
                message: "有效期不能为空",
                trigger: "change"
              }
            }
          }
        ],
        priorityLevel: [{ required: true, message: "请填写", trigger: "blur" }]
      },
      list: ['1'],
      oldArr: [],
      newArr: []
    };
  },
  created () {
    localStorage.removeItem('newData');
    // this.getONameSelect();
    // this.getPaymentAll()
  },
  methods: {
    bindleProductCode(val) {
      console.log(val);
      this.dataModule.productName = val.label || "";
      this.dataModule.productCode = val.value || "";
    },
    handleCloseType(val) {
      if (val === "1") {
        this.closeTypeDataType = false;
        console.log(val, "结算类型");
        this.$refs["dataModule"].fields.forEach(e => {
          if (
            e.prop == "clearRule" ||
            e.prop == "platformReceivable" ||
            e.prop == "commercialReceivable"
          )
            e.resetField();
        });
      } else {
        this.closeTypeDataType = true;
      }
    },
    bindleMCode(val) {
      console.log(val);
      this.dataModule.merchantName = val.label || "";
      this.dataModule.merchantCode = val.value || "";
    },
    // 规则类型
    handleTypeGadio(val) {
      console.log(val, "规则类型");
      if (val === "产品规则") {
        this.typeRadioDataType = true;
      } else {
        this.typeRadioDataType = false;
      }
    },
    setDateRange(value) {
      this.dataModule.beginTime = value;
      this.dataModule.contractStartDate = value[0];
      this.dataModule.contractEndDate = value[1];
    },
    bandleChanneType (val) {
      this.oldArr = JSON.parse(localStorage.getItem('newData'))
      this.newArr = []
      val.map(item=>{
        this.newArr.push(item.value)
      })
      localStorage.setItem('newData', JSON.stringify(this.newArr))

      console.log(this.newArr, '新数据')
      console.log(this.oldArr, '旧数据')

      console.log(this.oldArr ? this.oldArr.length : 0, '上一次数据')

      if (this.newArr.length > this.oldArr.length){
        console.log(val, '新增')
        for (var i = 0; i < this.newArr.length - this.oldArr.length; i++){
          let obj = {
            paymentChannelName: val[val.length - 1].label,
            paymentChannelCode: val[val.length - 1].value, // 渠道标识
            merchantSlottingFees: '',
            subMchId: '',
            platformSlottingFees: '',
            merchantCodeBusiness: '',
            merchantCodeAcquirer: '',
            subAppid: ''
          }
          this.channelListData.push(obj)
        }
      }else if (this.newArr.length < this.oldArr.length) {
        console.log('删除')
        for (var i =0; i < this.oldArr.length; i++) {
          if (this.newArr[i] != this.oldArr[i]) {
            this.channelListData.splice(i,1);
            break;
          }
        }
      }
    },
    getONameSelect () {
      appService.getRequest(`http://10.18.59.210:8080/admin/organization/findPageList?currentPage=1&pageSize=100`).then(res => {
        if (res.data.errorCode === 0) {
          this.oNameSelect = res.data.data.list.map(({organizationCode, organizationName}) => {
            return {
              value: organizationCode,
              label: organizationName
            }
          })
        }
      })
    },
    getPaymentAll () {
      appService.getRequest(`http://10.18.59.210:8082/api/paymentChannel/getAll`).then(res => {
        if (res.data.errorCode === 0) {
          console.log(res.data)

        }
      })
    },
    setDateRange (value) {
      this.dataModule.beginTime = value
      this.dataModule.contractStartDate = value[0]
      this.dataModule.contractEndDate = value[1]
    },
    goBack () {
      this.$router.go(-1)
    },
    getDitch (value) {
      console.log(value)
    },
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.$store.dispatch(`${namespace}/localUpdate`, this.dataModule);
          // this.dataModule = {};
          this.$router.push('commercial')
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleSubmitCancel(name) {
      this.$refs[name].resetFields();
    },
  },
  computed: {
    loading: function() {
      let result = this.$store.state[namespace].loading;
      return result;
    }
  }
};
</script>

<style lang="less">
.ditchBox {
  .ditchTitle{
    margin-bottom: 20px;
  }
  .ivu-date-picker{
    width: 100%
  }
}
</style>
